import logging
from runtime.nodelogger import NodeLogger
from datastore.resource import *
from datastore.uri import *
from runtime.service import *

class ApplicationFormService(Service):
    """
    
    """
    
    def cb_start(self, uri, action, res):
       
        self.spaces.set_process(Uri('internal:adaptor/application-form/'),self.cb_process)
                    
    def cb_stop ( self ):
        pass
    
    
    def cb_process(self, uri, action, res):
        
        if action == 'exists' :
            return True
        elif action in ['update']:
           
            if uri.split()[-1] == 'response':
                # we are not doing anything with the response so we can safely ignore it. 
                return    
        
            self.logger.log(logging.INFO, "Requesting SPEAR Application Form")
            
            response = Resource(type='term:eplanning/adaptor/application-form/data')
            response.dc_title("SPEAR Application Form")
            response.dc_description("SPEAR Application Form")

            query_data = res.query_data
            spear_ref_no = query_data['spearRef']
                                                                                   
            resources = self.datastore.find([(Uri('term:base/datastore/resource/type'),Uri('term:eplanning/spear/application')),(Uri('spearReferenceNumber'),spear_ref_no)])
            resource = resources[0]
            response.application = resource.application

            response.control = resource.control_dict
            response.h1_header = 'SPEAR Application Form'
            
            self.spaces.put(uri, res, spaces=True)
            
            # Our response will go to the request uri + 'response'
            response_uri = uri + 'response'
                                    
            self.spaces.put(response_uri, response)
            return response_uri
